package cn.test.server;

import cn.test.domain.Heart;
import cn.test.utils.ByteBufUtil;
import cn.test.utils.ByteHexUtil;
import cn.test.utils.DeviceData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/***
 *
 *
 * @Author: SJie
 * Date: 2019/12/19 下午5:44
 * Description:
 *
 */

public class ServerHandler extends ChannelInboundHandlerAdapter {
    int readIdleTimes = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("=== " + ctx.channel().remoteAddress() + " is active ===");
        DeviceData.add(ctx.channel());
        // 请求设备号
        int[] data = {0x00};
        ByteBuf byteBuf = ByteBufUtil.hexToByteBuf(data);
        ctx.channel().writeAndFlush(byteBuf);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        DeviceData.remove(ctx.channel());
        System.out.println("关闭连接");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        readIdleTimes = 0;
        byte[] data= ByteBufUtil.ByteBufToBytes(msg);
        String name = DeviceData.getDeviceName(ctx.channel());
        if (ByteHexUtil.byteToHex(data[0]) == 0xff) {
            System.out.println(name + ":设备心跳");
        } else {
            ctx.fireChannelRead(data);
        }


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;

        String eventType = null;
        switch (event.state()) {
            case READER_IDLE:
                eventType = "server:读空闲";

                break;
            case WRITER_IDLE:
                eventType = "server:写空闲";

                break;
            case ALL_IDLE:
                eventType = "server:读写空闲";
                readIdleTimes++; // 读写空闲的计数加1
                int[] data = {0xff};
                ByteBuf byteBuf = ByteBufUtil.hexToByteBuf(data);
                ctx.writeAndFlush(byteBuf);
// 不处理
                break;
        }
        //System.out.println(ctx.channel().remoteAddress() + "超时事件：" + eventType);
        if (readIdleTimes > 4) {
            DeviceData.remove(ctx.channel());
            System.out.println(" [server]读空闲超过4次，关闭连接");
            ctx.channel().writeAndFlush("you are out");
            ctx.channel().close();
        }
        //System.out.println("readIdleTimes:"+readIdleTimes);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();

        super.exceptionCaught(ctx, cause);
    }
}
